# coding=utf-8


class FilterSqlUtil(object):
    """过滤条件SQL"""

    def __init__(self):
        # 等于
        self.eq_filter = {}
        # 包含
        self.in_filter = {}
        # 不包含
        self.not_in_filter = {}
        # 模糊
        self.like_filter = {}

    def add_filter(self, filter_col, filter_type, filter_value):
        if filter_col == "brand":
            return self
        # 等于是单一字段对应单一值
        if filter_type == "eq" or filter_type == "=":
            self.eq_filter.setdefault(filter_col, filter_value)
        # in 可能存在单一字段对应多值
        if filter_type == "in":
            if filter_col in self.in_filter.keys():
                self.in_filter[filter_col].append(filter_value)
            else:
                self.in_filter.setdefault(filter_col, [filter_value])
        # not in 可能存在单一字段对应多值
        if filter_type == "not in":
            if filter_col in self.not_in_filter.keys():
                self.not_in_filter[filter_col].append(filter_value)
            self.not_in_filter.setdefault(filter_col, filter_value)
        # 等于是单一字段对应单一值
        if filter_type == "like":
            self.like_filter.setdefault(filter_col, filter_value)
        return self

    def get_filter_params(self):
        """获取过滤参数"""
        filter_dic = {}
        for key, value in self.eq_filter.items():
            filter_dic.setdefault(key, value)
        for key, value in self.in_filter.items():
            if key not in filter_dic.keys():
                filter_dic.setdefault(key, value)
            else:
                filter_dic[key].append(value)
        for key, value in self.not_in_filter.items():
            if key not in filter_dic.keys():
                filter_dic.setdefault(key, value)
            else:
                filter_dic[key].append(value)
        for key, value in self.like_filter.items():
            filter_dic.setdefault(key, value)
        return filter_dic

    def get_filter_sql(self):
        """获取过滤条件SQL"""
        filter_sql = ""
        for col, val in self.eq_filter.items():
            # filter_sql += f" AND {col} = '{val}' "
            filter_sql += f" AND {col} = :{col} "
        for col, values in self.in_filter.items():
            filter_sql += f" AND {col} in :{col} "
            # filter_sql += f" AND {col} in ("
            # for value in values:
            #     filter_sql += f"'{value}',"
            # filter_sql = filter_sql[:-1]
            # filter_sql += ") "
        for col, values in self.not_in_filter.items():
            filter_sql += f" AND {col} not in :{col} "
            # filter_sql += f" AND {col} not in ("
            # for value in values:
            #     filter_sql += f"'{value}',"
            # filter_sql = filter_sql[:-1]
            # filter_sql += ") "
        for col, val in self.like_filter.items():
            # filter_sql += f" AND {col} like '%{val}%' "
            filter_sql += f" AND {col} like '%:{col}%' "
        return filter_sql
